<?php

/**
 * This is the model class for table "article".
 *
 * The followings are the available columns in table 'article':
 * @property string $id
 * @property string $cid
 * @property string $type
 * @property string $title
 * @property string $sub_title
 * @property string $summary
 * @property string $thumb
 * @property string $cover
 * @property string $seo_title
 * @property string $seo_keywords
 * @property string $seo_description
 * @property integer $status
 * @property string $sort
 * @property string $author_id
 * @property string $author_name
 * @property string $scan_count
 * @property string $comment_count
 * @property integer $can_comment
 * @property integer $visibility
 * @property string $password
 * @property integer $flag_headline
 * @property integer $flag_recommend
 * @property integer $flag_slide_show
 * @property integer $flag_special_recommend
 * @property integer $flag_roll
 * @property integer $flag_bold
 * @property integer $flag_picture
 * @property string $template
 * @property string $created_at
 * @property string $updated_at
 * @property string $articleContent[] $articleContents
 */
class Article extends CActiveRecord
{
    const SINGLE_PAGE = 0;
    const ARTICLE = 1;
    const PRODUCT = 2;
    const CASES = 3;
    const DOWNLOAD = 4;
    const JOB = 5;

    const ARTICLE_PUBLISHED = 1;
    const ARTICLE_DRAFT = 0;

    const TAG_KEY_NAME = 'tag';
    const LIKE_KEY_NAME = 'like';

    /**
     * @var array
     */
    public $images;
    public $tag;
    public $content;

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{article}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('title, cid', 'required'),
			array('status, can_comment, visibility, flag_headline, flag_recommend, flag_slide_show, flag_special_recommend, flag_roll, flag_bold, flag_picture', 'numerical', 'integerOnly'=>true),
            array('cid, type, sort, author_id, scan_count, comment_count', 'numerical', 'integerOnly'=>true),
			array('created_at, updated_at', 'length', 'max'=>11),
			array('title, sub_title, summary, seo_title, seo_keywords, seo_description, author_name, password, template, tag', 'length', 'max'=>255),
			array(
			    'thumb',
                'file','on'=>'insert',
                'allowEmpty'=>true,
                'types'=>'jpg, jpeg, gif, png, bmp', 'maxSize'=>1024 * 1024 * 10 , // 10MB
                //'tooLarge'=>'文件大于10M，上传失败！请上传小于10M的文件！'
            ),
            array(
                'cover',
                'file','on'=>'insert',
                'allowEmpty'=>true,
                'types'=>'jpg, jpeg, gif, png, bmp', 'maxSize'=>1024 * 1024 * 10 , // 10MB
                //'tooLarge'=>'文件大于10M，上传失败！请上传小于10M的文件！'
            ),
            array(
                'images',
                'file','on'=>'insert',
                'allowEmpty' => true,
                'maxFiles' => 14,
                //'tooMany' => 'some error message',
                'maxSize' => 10*(1024*1024),	//10MB
                //'tooLarge' => 'some error message',
                'types' => 'jpg, jpeg, gif, png, bmp',	//extension names separated by space or comma
                //'wrongType' => 'some error message',
            ),
            //array('extend_field1,extend_filed2,extend_filed3,extend_filed4','default','value'=>''),
			array('content','default','value'=>''),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, cid, type, title, sub_title, summary, thumb, seo_title, seo_keywords, seo_description, status, sort, author_id, author_name, scan_count, comment_count, can_comment, visibility, password, flag_headline, flag_recommend, flag_slide_show, flag_special_recommend, flag_roll, flag_bold, flag_picture, template, created_at, updated_at, content, images, tag, cover', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		    'articleCategory'=>array(self::BELONGS_TO, 'Category', 'cid'),
            'articleContent'=>array(self::HAS_ONE, 'ArticleContent', array('aid'=>'id')),
            'articleTags'=>array(self::HAS_MANY, 'ArticleMetaTag', array('aid'=>'id')), // key=tag和key=like全部查询出来了
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'cid' => '分类',
			'type' => '类型',
			'title' => '标题',
			'sub_title' => '副标题',
			'summary' => '概要',
			'thumb' => '缩略图',
            'cover' => '封面',
			'seo_title' => 'SEO标题',
			'seo_keywords' => 'SEO关键字',
			'seo_description' => 'SEO描述',
			'status' => '状态',
			'sort' => '排序',
			'author_id' => '发布文章管理员id',
			'author_name' => '发布文章管理员用户名',
			'scan_count' => '浏览次数',
			'comment_count' => '评论次数',
			'can_comment' => '评论',
			'visibility' => '可见',
			'password' => '密码',
			'flag_headline' => '头条',
			'flag_recommend' => '推荐',
			'flag_slide_show' => '幻灯',
			'flag_special_recommend' => '特别推荐',
			'flag_roll' => '滚动',
			'flag_bold' => '加粗',
			'flag_picture' => '图片',
			'template' => '模板',
			'created_at' => '创建时间',
			'updated_at' => '修改时间',
            'content' => Yii::t('app', '内容'),
            'tag' => Yii::t('app', '标签'),
            'images' => Yii::t('app','内容配图'),
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id,true);
		$criteria->compare('cid',$this->cid,true);
		$criteria->compare('type',$this->type,true);
		$criteria->compare('title',$this->title,true);
		$criteria->compare('sub_title',$this->sub_title,true);
		$criteria->compare('summary',$this->summary,true);
		$criteria->compare('thumb',$this->thumb,true);
        $criteria->compare('cover',$this->cover,true);
        $criteria->compare('images',$this->images,true);
		$criteria->compare('seo_title',$this->seo_title,true);
		$criteria->compare('seo_keywords',$this->seo_keywords,true);
		$criteria->compare('seo_description',$this->seo_description,true);
		$criteria->compare('status',$this->status);
		$criteria->compare('sort',$this->sort,true);
		$criteria->compare('author_id',$this->author_id,true);
		$criteria->compare('author_name',$this->author_name,true);
		$criteria->compare('scan_count',$this->scan_count,true);
		$criteria->compare('comment_count',$this->comment_count,true);
		$criteria->compare('can_comment',$this->can_comment);
		$criteria->compare('visibility',$this->visibility);
		$criteria->compare('password',$this->password,true);
		$criteria->compare('flag_headline',$this->flag_headline);
		$criteria->compare('flag_recommend',$this->flag_recommend);
		$criteria->compare('flag_slide_show',$this->flag_slide_show);
		$criteria->compare('flag_special_recommend',$this->flag_special_recommend);
		$criteria->compare('flag_roll',$this->flag_roll);
		$criteria->compare('flag_bold',$this->flag_bold);
		$criteria->compare('flag_picture',$this->flag_picture);
		$criteria->compare('template',$this->template,true);
		$criteria->compare('created_at',$this->created_at,true);
		$criteria->compare('updated_at',$this->updated_at,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return Article the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

    /**
     * 前台获取分类ID及子孙分类产品
     * @param $cid
     * @param int $limitNum
     * @return array
     */
    public static function getArticles($cid, $limitNum=1){
        $allCat = Category::getDescendants($cid); //获取所有子分类信息
        $cidAll = '';
        foreach ($allCat as $k=>$v){
            if($k == 0){
                $cidAll .= $v['id'];
            }else{
                $cidAll .= ','.$v['id'];
            }
        }
        $cidArray = explode(',', $cidAll);
        $criteria = new CDbCriteria();
        $criteria->condition = 'status = '.self::ARTICLE_PUBLISHED;
        $criteria->compare('cid', $cidArray);//代表where cid IN (1,2,3,4,5);
        $criteria->order = 'sort ASC,id DESC';
        $criteria->limit = $limitNum;
        return self::model()->findAll($criteria);
    }


    /**
     * 获取Tag标签
     * @param $aid
     * @return string
     */
	public static function getArticleTags($aid){
        $tempModel = new ArticleMeta();
        $tags = $tempModel::model()->findAll('`key`=:key AND aid=:aid',array(':key'=>self::TAG_KEY_NAME,':aid'=>$aid));
        //var_dump($tags);
        $tagData = array();
        foreach ($tags as $key=>$tag){
            $tagData[] = $tag->attributes['value'];
        }
        return implode(',',$tagData);
    }

    /**
     * 获取喜欢的用户IP
     * @param $aid
     * @return string
     */
    public static function getArticleLikes($aid){
        $tempModel = new ArticleMeta();
        $likes = $tempModel::model()->findAll('`key`=:key AND aid=:aid',array(':key'=>self::LIKE_KEY_NAME,':aid'=>$aid));
        //var_dump($tags);
        $likeData = array();
        foreach ($likes as $key=>$like){
            $likeData[] = $like->attributes['value'];
        }
        return implode(',',$likeData);
    }

    /**
     * 上一篇文章
     * @param $id
     * @return array|mixed|null
     */
    public static function getPreArticle($id){
        return self::model()->find(array('select'=>array('id','title'),'condition'=>'id<'.$id.' AND type='.self::ARTICLE.'','order'=>'id DESC','limit'=>1));
    }

    /**
     * 下一篇文章
     * @param $id
     * @return array|mixed|null
     */
    public static function getNextArticle($id){
        return self::model()->find(array('select'=>array('id','title'),'condition'=>'id>'.$id.' AND type='.self::ARTICLE.'','order'=>'id ASC','limit'=>1));
    }

    /**
     * 热门文章
     * @param int $num
     * @return Article[]
     */
    public static function getHotArticles($num=10){
        return self::model()->findAll(array('select'=>array('id','title','created_at'),'condition'=>'type='.self::ARTICLE.'','order'=>'scan_count DESC,id DESC','limit'=>$num));
    }

    /**
     * 推荐文章
     * @param int $num
     * @return Article[]
     */
    public static function getRecommendArticles($num=10){
        return self::model()->findAll(array('select'=>array('id','title','created_at'),'condition'=>'type='.self::ARTICLE.' AND flag_recommend=1','order'=>'id DESC','limit'=>$num));
    }

    /**
     * 提前做数据处理，保存数据
     * @return bool
     */
    public function beforeSave()
    {
        parent::beforeSave(); // TODO: Change the autogenerated stub
        $this->seo_keywords = str_replace('，', ',', $this->seo_keywords);
        if(!$this->seo_description){
            $this->seo_description = Helper::cutStr(strip_tags($this->content), 200);
        }

        if($this->isNewRecord){
            $this->author_id = Yii::app()->user->id;
            $this->author_name = Yii::app()->user->name;
            $this->created_at = time();
        }else{
            $this->updated_at = time();
        }
        return true;
    }

    /**
     *
     */
    public function afterSave()
    {
        parent::afterSave(); // TODO: Change the autogenerated stub
        // Tags Save
        $articleMetaTag = new ArticleMetaTag();
        $articleMetaTag->setArticleTags($this->id, $this->tag);
        // Multi Images Save
        //$articleMetaTag = new ArticleMetaImages();
        //$articleMetaTag->setImages($this->id, $this->images);

        //content save
        if ( $this->isNewRecord ) {
            $contentModel = new ArticleContent();
            $contentModel->aid = $this->id;
        } else {
            $contentModel = ArticleContent::model()->find('aid=:aid',array(':aid'=>$this->id));
            if ($contentModel == null) {
                $contentModel = new ArticleContent();
                $contentModel->aid = $this->id;
            }
        }
        $contentModel->content = $this->content;
        $contentModel->save();
    }

    /**
     * @inheritdoc
     */
    public function afterFind()
    {
        //缩微图替换
        $this->thumb = $this->thumb ? $this->thumb : Yii::app()->baseUrl.'resource/frontend/images/none.jpg';
        $this->cover = $this->cover ? $this->cover : Yii::app()->baseUrl.'resource/frontend/images/none.jpg';
        //组图转换
        if($this->images)
            $image = explode(',', $this->images); //字符转转换数组
        else
            $image = '';

        //标签转换
        $this->tag = self::getArticleTags($this->id);

        //关联内容模型
        $this->content = ArticleContent::model()->find('aid=:aid',array(':aid' => $this->id))['content'];
        $this->summary = $this->summary ? $this->summary : Helper::clearCutStr($this->content,200,'...');
        parent::afterFind();
    }

    public function afterDelete()
    {
        parent::afterDelete(); // TODO: Change the autogenerated stub
        //文章删除后需要删除article_content表中相应的内容
        $contentModel = ArticleContent::model()->deleteAll('aid in (:aid)', array(':aid'=>$this->id));
    }
}
